<?php
namespace App\Http\Controllers;
use EasyWeChat\Factory;
use Illuminate\Http\Request;


class LoginController extends Controller {

    /**
     * 微信小程序登录，EasyWechat文档：https://easywechat.com/5.x/
     * @param Request $request
     */
    public function miniLogin(Request $request){
        try{
            $app=Factory::miniProgram(config('wechat.mini_program.default'));
            $res=$app->auth->session($request->input("code"));
            if(isset($res['openid'])){
                //cache()->set('session_key_'.$res['openid'],$res['openid'],300);//保存session_key，有效期5分钟
                $user=User::where('openid',$res['openid'])->first();
                $token=payload_encrypt(['user_id'=>$user->id]);
                return show_success(200,['token'=>$token]);
            }else{
                return show_error('登录失败',$res);
            }
        }catch(\Exception $e){
            return show_error('登录失败',$e->getMessage());
        }
    }

    /**
     * 获取微信小程序手机号，code为wx.getPhoneNumber返回的code,并非wx.login的code
     * @param Request $request
     */
    public function decryptMobile(Request $request){
        try{
            $res =Wechat::getPhoneByCode($request->input("code"));
            if($res&&isset($res['phone_info'])&&$res['phone_info']['phoneNumber']){
                $phone=$res['phone_info']['phoneNumber'];
            }
        }catch(\Exception $e){
            return show_error('获取手机号失败',$e->getMessage());
        }
    }
}
